package com.ant.androiddemo.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.ant.androiddemo.R;
import com.ant.androiddemo.bean.ItemBean;

import java.util.List;
import java.util.Random;

public class MyAdapter2 extends RecyclerView.Adapter<MyAdapter2.MyViewHolder>{

    private List<ItemBean> mBeanList;
    private LayoutInflater mLayoutInflater;
    private Context mContext;

    public MyAdapter2(Context context, List<ItemBean> mBeanList){
        this.mBeanList = mBeanList;
        this.mContext = context;
        mLayoutInflater = LayoutInflater.from(mContext);
    }
    @NonNull
    @Override
    public MyAdapter2.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = mLayoutInflater.inflate(R.layout.list_item_layout, parent, false);
        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyAdapter2.MyViewHolder holder, int position) {
        ItemBean newsBean = mBeanList.get(position);
        holder.mTvTitle.setText(newsBean.getTitle());
        holder.mTvTitle.setText(newsBean.getTitle());
        holder.mTvContent.setText(newsBean.getContent());
        holder.mIvImage.setImageResource(newsBean.getImgResId());
        Random random = new Random();
        int ran = random.nextInt(40)-10;
        holder.mIvImage.setLayoutParams(new RelativeLayout.LayoutParams(dp2px(100),dp2px(100+ran)));
        holder.rlContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext,"你点击了"+position, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private int dp2px(int dp) {
        final float scale = mContext.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    @Override
    public int getItemCount() {
        return mBeanList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder{

        TextView mTvTitle;
        TextView mTvContent;
        ImageView mIvImage;
        RelativeLayout rlContainer;


        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            this.mIvImage = itemView.findViewById(R.id.iv_img);
            this.mTvTitle = itemView.findViewById(R.id.tv_title);
            this.mTvContent = itemView.findViewById(R.id.tv_content);
            this.rlContainer = itemView.findViewById(R.id.rl_item_container);
        }
    }
}
